<!DOCTYPE html>
<html>
<head>
    <title>文创产品搜索</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .product-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .product-table th, .product-table td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
            font-size: 14px;
        }
        .product-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .product-table tr:hover {
            background-color: #f9f9f9;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .search-controls {
            margin: 20px 0;
            padding: 15px;
            background-color: #fffbf6;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .search-input {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-right: 10px;
            width: 200px;
        }
        .search-button {
            padding: 8px 16px;
            background-color: #c0a36c;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-button:hover {
            background-color: #a88c5a;
        }
        .product-card {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin: 10px 0;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .product-id {
            font-weight: bold;
            color: #c0a36c;
        }
        .product-name {
            font-size: 18px;
            margin: 5px 0;
        }
        .product-material {
            color: #666;
            font-size: 14px;
        }
        .product-details {
            margin-top: 10px;
            font-size: 12px;
            color: #888;
        }
        .product-image {
            width: 120px;
            height: 160px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 15px;
            float: left;
        }
        .product-content {
            overflow: hidden;
        }
        .product-card::after {
            content: "";
            display: table;
            clear: both;
        }
        .designer-info {
            background-color: #f8f9fa;
            padding: 8px;
            border-radius: 4px;
            margin-top: 8px;
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 1200px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <h2 style="max-width: 1200px; margin: 0 auto 20px auto; padding: 0 20px;">文创产品搜索</h2>

    <div class="search-controls">
        <div style="margin-bottom: 15px;">
            <label style="margin-right: 10px; font-weight: bold;">搜索方式:</label>
            <label style="margin-right: 10px;">
                <input type="radio" name="searchType" value="colors" checked> 按颜色
            </label>
            <label style="margin-right: 10px;">
                <input type="radio" name="searchType" value="designer_name"> 按设计师
            </label>
            <label>
                <input type="radio" name="searchType" value="product_id"> 按产品ID
            </label>
        </div>
        
        <input type="text" id="searchInput" class="search-input" placeholder="输入搜索关键词...">
        <button onclick="loadAllProducts()" class="search-button">显示全部</button>
        <div style="margin-top: 10px; font-size: 12px; color: #666;">
            提示：颜色搜索支持多字符（如"红黄"），将匹配包含红、黄或红黄的产品；产品ID搜索支持精确或部分匹配
        </div>
    </div>

    <div id="loading" class="loading">正在加载产品数据...</div>
    <div id="error" class="error" style="display: none;"></div>
    
    <div id="productContainer">
        <!-- 产品数据将在这里显示 -->
    </div>

    <script src="../static/js/common.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../static/js/ejj_functions.js"></script>
    <script>
        let allProducts = []; // 存储所有产品数据
        
        // 获取产品图片URL
        function getProductImageUrl(productId) {
            if (!productId) return '/static/images/default_cover.jpg';
            return `/serve_jade_image?product_id=${productId}`;
        }
        
        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            // 页面加载时立即检查登录状态
            checkLoginStatusAndToggleButtons();
            
            loadAllProducts();
            
            // 添加搜索方式改变事件
            document.querySelectorAll('input[name="searchType"]').forEach(radio => {
                radio.addEventListener('change', filterProducts);
            });
            
            // 添加输入框实时搜索（防抖）
            let searchTimeout;
            document.getElementById('searchInput').addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(filterProducts, 300);
            });
        });

        // 获取所有产品数据
        function loadAllProducts() {
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const container = document.getElementById('productContainer');
            
            if (loading) loading.style.display = 'block';
            if (error) error.style.display = 'none';
            if (container) container.innerHTML = '';

            fetch('/get_culture_product_list')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (loading) loading.style.display = 'none';
                    if (data.res === 'ok' && data.data) {
                        allProducts = data.data; // 保存所有产品数据
                        filterProducts(); // 应用当前筛选条件
                    } else {
                        throw new Error('数据格式错误');
                    }
                })
                .catch(error => {
                    if (loading) loading.style.display = 'none';
                    if (error) {
                        error.style.display = 'block';
                        error.textContent = '加载失败: ' + error.message;
                    }
                });
        }

        // 筛选产品
        function filterProducts() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const searchType = document.querySelector('input[name="searchType"]:checked').value;
            
            let filteredData = allProducts;
            
            // 关键词搜索
            if (searchTerm) {
                filteredData = filteredData.filter(product => {
                    const fieldValue = product[searchType];
                    if (!fieldValue) return false;
                    
                    const fieldValueLower = fieldValue.toLowerCase();
                    
                    // 对于颜色搜索，支持多字符匹配（OR逻辑）
                    if (searchType === 'colors') {
                        // 检查是否包含搜索词中的任意字符或整个搜索词
                        return searchTerm.split('').some(char => fieldValueLower.includes(char)) || 
                               fieldValueLower.includes(searchTerm);
                    } else {
                        // 设计师字段使用原来的包含匹配
                        return fieldValueLower.includes(searchTerm);
                    }
                });
            }
            
            displayProducts(filteredData);
        }

        // 显示产品数据
        function displayProducts(products) {
            const container = document.getElementById('productContainer');
            
            if (products.length === 0) {
                container.innerHTML = '<div class="loading">没有找到匹配的产品</div>';
                return;
            }

            let html = '<div class="product-list">';
            
            products.forEach(product => {
                const imageUrl = getProductImageUrl(product.product_id);
                html += `
                    <div class="product-card">
                        <img src="${imageUrl}" class="product-image" alt="${product.product_name || '产品图片'}" 
                             onerror="this.src='/static/images/default_cover.jpg'"
                             style="cursor: pointer;" onclick="showJadeImages('${product.product_id ? product.product_id.trim() : ''}')">
                        <div class="product-content">
                            <div class="product-id">${product.product_id || '无编号'}</div>
                            <div class="product-name">${product.product_name || '未命名产品'}</div>
                            ${product.product_descript ? `<div class="product-material">${product.product_descript}</div>` : ''}
                            
                            <div class="product-details">
                                ${product.type ? `<div><strong>类型:</strong> ${product.type}</div>` : ''}
                                ${product.materials ? `<div><strong>材质:</strong> ${product.materials}</div>` : ''}
                                ${product.wu_xings ? `<div><strong>五行:</strong> ${product.wu_xings}</div>` : ''}
                                ${product.colors ? `<div><strong>颜色:</strong> ${product.colors}</div>` : ''}
                                ${product.size ? `<div><strong>尺寸:</strong> ${product.size}</div>` : ''}
                            </div>
                            
                            ${product.designer_name || product.designer_company ? `
                            <div class="designer-info">
                                <strong>设计信息:</strong>
                                ${product.designer_name ? `设计师: ${product.designer_name}` : ''}
                                ${product.designer_company ? ` | 公司: ${product.designer_company}` : ''}
                                ${product.designed_date ? ` | 设计日期: ${formatDate(product.designed_date)}` : ''}
                            </div>
                            ` : ''}
                            
                            ${product.comment ? `<div style="margin-top: 8px;"><strong>备注:</strong> ${product.comment}</div>` : ''}
                        </div>
                    </div>
                `;
            });

            html += '</div>';
            container.innerHTML = html;
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN');
            } catch (e) {
                return dateString;
            }
        }

        // 检查登录状态并控制状态栏和返回按钮显示
        function checkLoginStatusAndToggleButtons() {
            // 从状态栏获取登录状态 - 检查用户名是否为"未登录"
            const usernameElement = document.querySelector('.username');
            const isLoggedIn = usernameElement && usernameElement.textContent !== '未登录';
            
            console.log('登录状态检查:', isLoggedIn, usernameElement ? usernameElement.textContent : '无用户名元素');
            
            // 控制状态栏的显示
            const statusBar = document.querySelector('.status-bar');
            if (statusBar) {
                statusBar.style.display = isLoggedIn ? 'flex' : 'none';
            }
            
            // 控制返回主菜单按钮的显示
            const backButton = document.querySelector('a[href="/ej_index"]');
            if (backButton) {
                backButton.style.display = isLoggedIn ? 'inline-block' : 'none';
            }
            
            // 调整页面顶部内边距
            if (!isLoggedIn) {
                document.body.style.paddingTop = '0';
            } else {
                document.body.style.paddingTop = '60px';
            }
        }
    </script>
</body>
</html>
